﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using iOak.Business.Users;
using iOak.Business.Resumes;
using iOak.Business.Directory;
using iOak.Domain.Directory;
using iOak.Domain.Users;
using System.Configuration;
using iOak.Domain.Resumes;
using System.IO;
using System.Globalization;

namespace iOak.Web.Modules
{
    public partial class CompanyEditControl : System.Web.UI.UserControl
    {
        private UserService _userService = new UserService();
        private CompanyService _companyService = new CompanyService();
        private PicklistValueService _picklistValueService = new PicklistValueService();
        private WorkAssistant _workassistant = new WorkAssistant();

        /// <summary>
        /// 页面模式0-企业界面;1-管委会界面
        /// </summary>
        public int PageMode
        {
            set { this.ViewState["PageMode"] = value; }
            get { return int.Parse(this.ViewState["PageMode"].ToString()); }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Page.IsPostBack)
            {
                BindControl();
                BindData();
            }
        }

        private void BindControl()
        {
            var employeesList = _picklistValueService.RetrieveMultiple(PickListEnum.EMPLOYEES);
            ddlEmployeesCode.DataSource = employeesList;
            ddlEmployeesCode.DataTextField = "Name";
            ddlEmployeesCode.DataValueField = "Value";
            ddlEmployeesCode.DataBind();
            ddlEmployeesCode.Items.Insert(0, new ListItem("", ""));

            var companyTypeList = _picklistValueService.RetrieveMultiple(PickListEnum.COMPANYTYPE);
            ddlCompanyTypeCode.DataSource = companyTypeList;
            ddlCompanyTypeCode.DataTextField = "Name";
            ddlCompanyTypeCode.DataValueField = "Value";
            ddlCompanyTypeCode.DataBind();
            ddlCompanyTypeCode.Items.Insert(0, new ListItem("", ""));
        }

        private void BindData()
        {
            Company company = GetCompany();
            txtAddress.Text = company.Address;
            txtAssuredLaborCode.Text = company.AssuredLaborCode;
            txtBankAccountNo.Text = company.BankAccountNo;
            txtBankName.Text = company.BankName;
            lblCompanyName.Text = company.CompanyName;
            txtCompanyName.Text = company.CompanyName;
            txtContactFax.Text = company.ContactFax;
            txtContactPerson.Text = company.ContactPerson;
            txtContactPhone.Text = company.ContactPhone;
            txtDescription.Text = company.Description;
            txtEmail.Text = company.ContactEmail;
            txtOrganizationCode.Text = company.OrganizationCode;
            txtPostalCode.Text = company.PostalCode;
            chkIs530.Checked = company.Is530;
            if (company.IsActive.HasValue && company.IsActive.Value)
            {
                chkIsActive.Checked = true;
            }
            if (PageMode == 0)
            {
                ph530.Visible = company.Is530;
                //未审核
                if (!company.IsActive.HasValue)
                {
                    phActive.Visible = false;
                    phNoActive.Visible = false;
                    lblCompanyName.Visible = false;
                }
                //审核未通过
                else if (!company.IsActive.Value)
                {
                    phNoChecked.Visible = false;
                    phActive.Visible = false;
                    lblCompanyName.Visible = false;
                }
                //审核通过
                else
                {
                    phNoChecked.Visible = false;
                    phNoActive.Visible = false;
                    txtCompanyName.Visible = false;
                }
            }
            else
            {
                phActive.Visible = false;
                phNoActive.Visible = false;
                phNoChecked.Visible = false;
                ph530.Visible = false;
                lblCompanyName.Visible = false;
            }
            ddlEmployeesCode.SelectedValue = company.EmployeesCode.ToString();
            ddlCompanyTypeCode.SelectedValue = company.CompanyTypeCode.ToString();
            trIs530.Visible = PageMode == 1;
            trIsActive.Visible = PageMode == 1;

            if (company.BusinessLicense != null)
            {
                SetImageClick(company.CompanyId, true);
            }
        }

        protected void btnOk_Click(object sender, EventArgs e)
        {
            if (txtCompanyName.Visible)
            {
                if (!ValidateData())
                {
                    return;
                }
            }
            Company company = GetCompany();
            company.Address = txtAddress.Text;
            company.AssuredLaborCode = txtAssuredLaborCode.Text;
            company.BankAccountNo = txtBankAccountNo.Text;
            company.BankName = txtBankName.Text;
            company.CompanyName = lblCompanyName.Text;
            company.CompanyName = txtCompanyName.Text;
            company.ContactFax = txtContactFax.Text;
            company.ContactPerson = txtContactPerson.Text;
            company.ContactPhone = txtContactPhone.Text;
            company.Description = txtDescription.Text;
            company.ContactEmail = txtEmail.Text;
            company.OrganizationCode = txtOrganizationCode.Text;
            company.PostalCode = txtPostalCode.Text;
            company.Is530 = chkIs530.Checked;
            company.IsActive = chkIsActive.Checked;
            if (ddlEmployeesCode.SelectedIndex != 0)
            {
                company.EmployeesCode = int.Parse(ddlEmployeesCode.SelectedValue);
            }

            if (ddlCompanyTypeCode.SelectedIndex != 0)
            {
                company.CompanyTypeCode = int.Parse(ddlCompanyTypeCode.SelectedValue);
            }
            _companyService.Update(company);

            if (PageMode == 1)
            {
                this.Response.Redirect("/Administration/CompanyList.aspx");
            }
        }

        protected void btnPostBack_Click(object sender, EventArgs e)
        {
            switch (hidEventName.Value)
            {
                case "delete":
                    Company company = GetCompany();
                    company.BusinessLicense = null;
                    _companyService.Update(company);
                    SetImageClick(company.CompanyId, false);
                    break;
            }
        }

        private Company GetCompany()
        {
            Company company = null;
            if (PageMode == 0)
            {
                company = _companyService.Retrieve(_workassistant.CurrentUser.CompanyId);
            }
            else
            {
                Guid companyId = Guid.Parse(this.Request.QueryString["companyId"]);
                company = _companyService.Retrieve(companyId);
            }
            return company;
        }

        protected bool ValidateData()
        {
            Company checkCompany = GetCompany();
            Company company = _companyService.GetByName(txtCompanyName.Text);
            if (company != null && !company.CompanyId.Equals(checkCompany.CompanyId))
            {
                this.Parent.Page.ClientScript.RegisterStartupScript(Page.GetType(), "showWarnning", "$(document).ready(function(){jAlert('企业名称已存在！');});", true);
                return false;
            }
            return true;
        }

        protected void btnUpload_Click(object sender, EventArgs e)
        {
            int allowFileSize = int.Parse(ConfigurationManager.AppSettings["fileSize"]);
            if (fileChose.PostedFile.ContentLength > allowFileSize)
            {
                this.Parent.Page.ClientScript.RegisterStartupScript(Page.GetType(), "showWarnning", "$(document).ready(function(){jAlert('请上传不超过" + (allowFileSize / 1024) + "K的图片！');});", true);
                return;
            }
            else
            {
                // 判断文件格式
                string fileExtension = Path.GetExtension(fileChose.FileName).ToUpper(CultureInfo.CurrentCulture);
                if (!fileExtension.Equals(".JPG", StringComparison.Ordinal) && !fileExtension.Equals(".GIF", StringComparison.Ordinal))
                {
                    this.Parent.Page.ClientScript.RegisterStartupScript(Page.GetType(), "showWarnning", "$(document).ready(function(){jAlert('请选择jpg或gif的图片文件！');});", true);
                    return;
                }
            }
            Company company = GetCompany();
            company.BusinessLicense = fileChose.FileBytes;
            _companyService.Update(company);
            SetImageClick(company.CompanyId, true);
        }

        private void SetImageClick(Guid companyId, bool allowClick)
        {
            if (allowClick)
            {
                imgBusinessLicense.ImageUrl = "/Popups/AttachementShow.ashx?CompanyId=" + companyId.ToString();
                imgBusinessLicense.Style.Add("cursor", "pointer");
                imageShow.ImageUrl = imgBusinessLicense.ImageUrl;
                modalPopupExtenderShowImages.Enabled = true;
            }
            else
            {
                imgBusinessLicense.Style.Remove("cursor");
                modalPopupExtenderShowImages.Enabled = false;
            }
        }
    }
}